package com.jjh.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 存储字符串值
    public void setString(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    // 获取字符串值
    public String getString(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

    // 删除字符串值
    public void deleteString(String key) {
        redisTemplate.delete(key);
    }

    // 存储hash值
    public void setHash(String key, Map<String, Object> hash) {
        redisTemplate.opsForHash().putAll(key, hash);
    }

    // 获取hash值
    public Map<Object, Object> getHash(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    // 获取hash指定字段的值
    public Object getHashField(String key, String field) {
        return redisTemplate.opsForHash().get(key, field);
    }

    // 删除hash值
    public void deleteHash(String key, Object... fields) {
        redisTemplate.opsForHash().delete(key, fields);
    }

    // 设置过期时间（秒）
    public void expire(String key, long seconds) {
        redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }
}
